<?php

/***
 * Name:       TinyMVC
 * About:      An MVC application framework for PHP
 * Copyright:  (C) Mana, All rights reserved.
 * Author:     Nguyen Phu Quang, quang [at] mana [dot] vn
 * License:    private 
 ***/

// ------------------------------------------------------------------------

/**
 * TinyMVC_PDO
 *
 * PDO database access
 * compile PHP with --enable-pdo (default with PHP 5.1+)
 *
 * @package		TinyMVC
 * @author		Monte Ohrt
 */

class TinyMVC_Mongo
{
 	/**
	 * $pdo
	 *
	 * the Mongo object handle
	 *
	 * @access	public
	 */
  var $mongo = null;

 	/**
	 * $result
	 *
	 * the query result handle
	 *
	 * @access	public
	 */
  var $dbs = array();

 	/**
	 * class constructor
	 *
	 * @access	public
	 */
  function __construct($config) {

   if(!class_exists('Mongo',false))
     throw new Exception("PHP Mongo package is required.");

   if(empty($config))
     throw new Exception("database definitions required.");

   if(empty($config['charset']))
    $config['charset'] = 'UTF-8';

    /* attempt to instantiate PDO object and database connection */
    try {
      $options = array();
      if (!empty($config['persistent'])) $options['persist'] = true;
      if (!empty($config['user']) || !empty($config['pass'])) {
        $user_pass = "{$config['user']}:{$config['pass']}@";
      } else {
        $user_pass = '';
      }
      if (!empty($config['port'])) {
        $port = ':'.$config['port'];
      } else {
        $port = '';
      }
      $this->mongo = new Mongo(
        "{$user_pass}{$config['host']}".$port,
        $options
      );
    } catch (Exception $e) {
        throw new Exception(sprintf("Can't connect to Mongo database '{$config['type']}'. Error: %s",$e->getMessage()));
    }
  }

  function getDb($dbname) {
    if (null==($db=@$this->dbs[$dbname])) {
      $db = $this->mongo->selectDb($dbname);
    }
    return $db;
  }
}
